package com.lzxr.test.service.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.BeanHandler;
import cn.hutool.db.sql.Query;
import com.lzxr.test.entity.UriView;
import com.lzxr.test.service.UriService;

import java.sql.SQLException;
import java.util.List;

public class UriServiceImpl implements UriService {
    private static final String TABLE_NAME = "api_view_num";
    @Override
    public void save(UriView data) {
        UriView ret = getOne(data.getUri());
        if(ret == null){
            // 新增
            data.setViewNum(1);
            try {
                Db.use().insert(Entity.create(TABLE_NAME).parseBean(data, true, true));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } else {
            // 修改
            try {
                Db.use().update(Entity.create(TABLE_NAME).set("view_num", ret.getViewNum() + 1), Entity.create(TABLE_NAME).set("uri", data.getUri()));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public UriView getOne(String uri) {
        UriView uriView = null;
        try {
            uriView = (UriView) Db.use().find(Query.of(Entity.create(TABLE_NAME).set("uri", uri)), new BeanHandler(UriView.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return uriView;
    }

    @Override
    public List<UriView> getList() {
        List<UriView> apiViewNum = null;
        try {
            apiViewNum = Db.use().findAll(Entity.create(TABLE_NAME), UriView.class);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return apiViewNum;
    }

}
